"""



Last Modified: $Id: commandclient.py 14 2005-05-17 20:36:03Z gustavo $

@author: U{Gustavo Sverzut Barbieri <barbieri@gmail.com>}
@license: GNU GPL
@copyright: (C) 2005 Gustavo Sverzut Barbieri
@version: $Rev: 14 $
"""


import sys
import socket
import readline
import code
from commandserver import command_send, command_recv

class CommandClientConsole( code.InteractiveConsole ):
    """Interactive Python Console with tab-completion and utilities to connect
    to server and send/receive commands from a Command Server.

    @see: L{commandserver.command_send}, L{commandserver.command_recv},
    L{commandserver.CommandRequestHandler}.
    """
    def __init__( self, locals=None ):
        code.InteractiveConsole.__init__( self, locals )
        readline.parse_and_bind( 'tab: complete' )
    # __init__()
# CommandClientConsole


def connect( host, port ):
    """Connect to a Command Server with a CommandRequestHandler-like handler.

    @param host: hostname to connect to.
    @param port: port at host to connect to.
    """
    global sock
    sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    sock.connect( ( host, port ) )
# connect()

def getsock():
    """Returns the socket object.

    @return: socket object used for send and receive. You can perform any low
    level stuff with it.
    @rtype L{socket<socket.socket>}

    @see: L{socket<socket.socket>}
    """
    try:
        return sock
    except NameError:
        print >> sys.stderr, "You need to connect() first"
# getsock()

def send( command, data ):
    """Send command and data to server.

    @param command: what command to send.
    @param data: data to send as command argument.

    @see: L{commandserver.command_send}
    """
    return command_send( sock.send, command, data )
# send()


def recv():
    """Receive data from server.

    @return: a tuple C{(command, data)}.
    @rtype: L{tuple}

    @see: L{commandserver.command_recv}
    """
    return command_recv( sock.recv )
# recv()


l = {}
l.update( locals() )
del l[ 'CommandClientConsole' ]
del l[ 'l' ]

ccc = CommandClientConsole( l )
ccc.interact( """\
Command Client Console (CCC).

You can connect(host,port) to a server and then send(command,data) to it or
recv() data.

The socket object is 'sock'.

Other than these functionality it's conventional python interpreter.
""" )
